const defaultAttr = () => ({
	gl: null,
	vertices: [],
	geoData: [],
	size: 2,
	attrName: 'a_Position',
	count: 0,
	types: ['POINTS']
});
export default class Poly {
	constructor(attr) {
		Object.assign(this, defaultAttr(), attr);
		this.init();
	}
	init() {
		const { count, size, gl } = this;
		if (!gl) return;
		// 缓冲对象
		const vertexBuffer = gl.createBuffer();
		// 绑定缓冲对象
		gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
		// 写入数据
		this.updateBuffer();
		this.updateCount();
		// 获取 attribute 变量
		const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
		// 修改 attribute 变量
		gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
		// 赋能批处理
		gl.enableVertexAttribArray(a_Position);
	}
	
	updateBuffer() {
		const { gl, vertices } = this;
		gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
	}
	updateCount() {
		this.count = this.vertices.length / this.size;
	}
	// 添加顶点
	addVertice(...args) {
		this.vertices.push(...args);
		this.updateBuffer();
		this.updateCount();
	}
	// 删除顶点
	popVertice(...args) {
		const { vertices, size } = this;
		const len = vertices.length;
		vertices.splice(len - size, len);
		this.updateCount();
	}
	// 修改顶点
	setVertice(index, ...args) {
		const { vertices, size } = this;
		const i = index * size;
		args.forEach((arg, argIndex) => {
			vertices[i + argIndex] = arg;
		});
	}
	// 更新顶点数据
	updateVertices(args) {
		const { geoData } = this;
		const vertices = [];
		geoData.forEach(data => {
			args.forEach(key => {
				vertices.push(data[key]);
			})
		});
		this.vertices = vertices;
	}
	// 绘制
	draw(types = this.types) {
		const { gl, count } = this;
		for (let type of types) {
			gl.drawArrays(gl[type], 0, count);
		}
	}
}